package com.example.administrator.thread_test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bean.book;
import bean.bookAdapter;

public class SoupActivity extends Activity {
    Handler handler = new Handler();
    Button btn;
    TextView tv;
    String search_str = "";
    EditText et2 ;
    ListView list;


    public static Map<String, String> book_data = null;
//
//    static {
//        createMap = new HashMap<String, String>();
//        createMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/56.0");
//        createMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//        createMap.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
//        createMap.put("Accept-Encoding", "gzip, deflate, br");
//        createMap.put("Referer", "https://www.toutiao.com/ch/news_military/");
//        createMap.put("Connection", "keep-alive");
//        createMap.put("Upgrade-Insecure-Requests", "1");
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soup);
//        String msg = "";
//        String httpUrl="网址";
        et2 = (EditText)findViewById(R.id.et_search);
        list = (ListView)findViewById(R.id.list_book);
//         tv = (TextView)findViewById(R.id.tv2);
         btn =(Button)findViewById(R.id.bt2);
//        tv.setMovementMethod(ScrollingMovementMethod.getInstance());
        btn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        search_str = et2.getText().toString();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                final String httpUrl= "http://opac.lib.wust.edu.cn:8080/opac/openlink.php?strSearchType=title&strText="+search_str+"&loginsubmit.x=0&loginsubmit.y=0";
                                final ArrayList<book> r= crawler(httpUrl);
                                final String r_tran ="";



                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        bookAdapter bookAdapter = new bookAdapter(SoupActivity.this,R.layout.vlist,r);
                                        list.setAdapter(bookAdapter);
                                        list.setOnItemClickListener(
                                                new AdapterView.OnItemClickListener() {
                                                    @Override
                                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                        book book3 = r.get(position);
                                                       // Toast.makeText(getApplicationContext(),book3.getBook_link(),Toast.LENGTH_SHORT).show();
                                                        Intent intent = new Intent(getApplicationContext(),detailActivity.class);
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString("id",book3.getBook_link());
                                                        intent.putExtras(bundle);
                                                        startActivityForResult(intent,200);
                                                    }
                                                }
                                        );
                                    }
                                });
                            }
                        }).start();
                    }
                }
        );



    }
//    public String getData(String url)
//    {
//        Jsoup j ;
//        try {
//            Document document = Jsoup.connect(url).get();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }



    public ArrayList<book> crawler(String httpUrl)
    {
        String msg = ""; //服务器返回结果
        try {
            URL url = new URL(httpUrl);
//创建HttpURLConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection)
                    url.openConnection();

            httpURLConnection.setConnectTimeout(5000); //设置连接超时为5秒
            httpURLConnection.setRequestMethod("GET"); //设置请求方式(默认为get)
            httpURLConnection.setRequestProperty("Charset", "uft-8"); //设置uft-8字符集
            httpURLConnection.connect();
//获得服务器反馈状态信息
//200：表示成功完成(HTTP_OK)， 404：请求资源不存在(HTTP_NOT_FOUND)
            int code = httpURLConnection.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
//接收服务器返回的信息（输入流）
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    msg+=line;
                }
//关闭缓冲区和连接
                bufferedReader.close();
                httpURLConnection.disconnect();
            }
//            Log.v("ajax",msg);
//                return msg;
//复制前页get流程代码…
        } catch (IOException e) {
            e.printStackTrace();
        }
        String res = "";
        Document doc = Jsoup.parse(msg);
        //Log.v("ajax",doc.toString());
        Elements elems = doc.getElementsByClass("book_list_info");
        ArrayList<book> data = new ArrayList<>() ;
        for (Element link : elems) {
//                                    String linkHref = link.attr("href");
            Elements item = link.getElementsByTag("h3");
            Elements item2 = link.getElementsByTag("a");
            String linkText = item2.text();
            String link2 = item2.attr("href");
            res = res+" "+linkText;

            Elements item_p = link.getElementsByTag("p");
            String p_val = item_p.text();
            Log.v("acc",linkText);


            String[] book_temp = linkText.split(" ");



//            Log.v("name",linkText);
            try{
                String book_index = book_temp[book_temp.length-1];
                String book_first[] = linkText.split("\\.");
                int item3 = book_first[0].length();
//                String temp[] = linkText.substring(5,linkText.length() - book_index.length()).split("\\.");
                String book_name = linkText.substring(1+item3,linkText.length() - book_index.length());
                String book_link = link2;
                String temp3[] = p_val.split(" ");
                String publish_time = temp3[temp3.length-3];
                String publish = temp3[temp3.length-4];
                String count = temp3[1];
                String author = p_val.substring(14,p_val.length()-1-12-publish.length());

                book book_temp2 = new book(book_name,author,publish,publish_time,count,book_link);
                data.add(book_temp2);
                Log.v("name",book_name);
            }catch (Exception e)
            {
                e.printStackTrace();
            }


        }



        return data;
    } //end scawler




}

